package network

import (
	"github.com/coreos/go-iptables/iptables"
	"github.com/vishvananda/netlink"
	"io"
	"net"
	"os"
)

func SetRoute(interfaceName string, subnet *net.IPNet) error {
	iface, err := netlink.LinkByName(interfaceName)
	if err != nil {
		return err
	}
	route := netlink.Route{
		LinkIndex: iface.Attrs().Index,
		Dst: &net.IPNet{
			IP:   subnet.IP,
			Mask: subnet.Mask,
		},
		Src: nil,
	}
	if err := netlink.RouteAdd(&route); err != nil {
		return err
	}
	return nil
}

func setupNat(interfaceName string, IPRange *net.IPNet) error {
	table, err := iptables.New()
	if err != nil {
		return err
	}

	// 设置nat
	if err = table.Append("nat", "POSTROUTING",
		"-s", IPRange.String(), "!", "-o", interfaceName, "-j", "MASQUERADE"); err != nil {
		return err
	}

	// 防止包被丢弃
	if err = table.Append("filter", "FORWARD",
		"-i", interfaceName, "-j", "ACCEPT"); err != nil {
		return err
	}
	if err = table.Append("filter", "FORWARD",
		"-o", interfaceName, "-j", "ACCEPT"); err != nil {
		return err
	}
	return nil
}

// 开启IPV4转发
func enableIpv4Forward() {
	file, _ := os.OpenFile("/proc/sys/net/ipv4/ip_forward", os.O_RDWR, 0)
	forward := make([]byte, 1)
	_, _ = file.Read(forward)
	_, _ = file.Seek(0, io.SeekStart)
	if forward[0] == '0' {
		logger.Debug("enable ipv4 forward")
		_, _ = file.Write([]byte("1\n"))
	}
	_ = file.Close()
}

// 获取子网的第一个IP
func getGateway(CIDR *net.IPNet) net.IP {
	mask := CIDR.Mask
	ip := CIDR.IP
	ip = ip.Mask(mask)
	ip.To4()[3] += 1
	return ip
}